package com.xoa.service.im;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

import javax.annotation.Resource;

import com.xoa.util.Convert;
import com.xoa.util.ModuleEnum;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.xoa.dao.enclosure.AttachmentMapper;
import com.xoa.model.enclosure.Attachment;
import com.xoa.service.enclosure.EnclosureService;
import com.xoa.util.GetUUID;

@Service
public class ImEnclosureService {
    @Resource
    AttachmentMapper attachmentMapper;


    public void saveAttachment(Attachment attachment) {
        attachmentMapper.insertSelective(attachment);

    }

    public Attachment findByAttachId(int attachId) {
        Attachment a = attachmentMapper.findByAttachId(attachId);
        return a;
    }

    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年4月26日 下午6:57:35
     * 方法介绍:   查找最后的附件信息
     * 参数说明:   @return
     *
     * @return Attachment 附件信息
     */
    public Attachment findByLast() {
        Attachment att = attachmentMapper.findByLast();
        return att;
    }


    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年4月26日 下午6:56:58
     * 方法介绍:   上传接口
     * 参数说明:   @param files 上传文件
     * 参数说明:   @param company 公司名
     * 参数说明:   @param module 模块名
     * 参数说明:   @return
     *
     * @return List<Attachment>  附件信息集合
     * @throws IOException
     */

    public synchronized List<Attachment> upload(MultipartFile[] files, String types, String module, String company, boolean isMobile) throws IOException {
        if (files.length == 0) {
            return null;
        }
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        String os = System.getProperty("os.name");
        StringBuffer sb = new StringBuffer();
          StringBuffer buffer=new StringBuffer();
        if(os.toLowerCase().startsWith("win")){
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if(uploadPath.indexOf(":")==-1){
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath()+ File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if(basePath.indexOf("/xoa")!=-1){
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2=basePath.substring(0,index);
                }
                sb = sb.append(str2 + "/xoa");
            }
            sb.append(uploadPath);
            buffer=buffer.append(rb.getString("upload.win"));
        }else{
            sb=sb.append(rb.getString("upload.linux"));
            buffer=buffer.append(rb.getString("upload.linux"));
        }
        List<Attachment> list = new ArrayList<Attachment>();
        //当前年月
        String ym = new SimpleDateFormat("yyMM").format(new Date());
        //存储路径
//        String path = sb.toString() + System.getProperty("file.separator") + "attach" + System.getProperty("file.separator") +
//                company + System.getProperty("file.separator") + module + System.getProperty("file.separator") + ym;
        String path = sb.toString() + System.getProperty("file.separator") +
                company + System.getProperty("file.separator") + module + System.getProperty("file.separator") + ym;
        Attachment attachment = new Attachment();
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            Long filesize=file.getSize();
            if (!file.isEmpty()) {
                // 获得原始文件名
                String fileName = file.getOriginalFilename().trim();
                //String fileName = new String(file.getOriginalFilename().getBytes("gbk"),"utf-8");
                String attachID = String.valueOf(Math.abs((int) System.currentTimeMillis()));
                StringBuffer s = new StringBuffer();
                if (os.toLowerCase().startsWith("win")) {
                    s.append(fileName);
                } else {
                    s.append(fileName);
                }
                String sf = attachID + "." + s.toString();
                String newFileName = sf;
                File dir = new File(path);
                File newFile = null;
                if (!file.isEmpty()) {
                    try {
                        if (!dir.exists()) {
                            dir.mkdirs();
                        }
                        newFile = new File(dir, newFileName);
                        // 转存文件
                        if (!newFile.exists()) {
                            newFile.createNewFile();
                        }
                        file.transferTo(newFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                byte isImg = 3;
                //获取后缀名
                String type = fileName.substring(fileName.indexOf(".") + 1);
                String[] imagType = {"jpg", "png", "bmp", "gif", "JPG", "PNG", "BMP", "GIF"};
                List<String> imageTyepLists = Arrays.asList(imagType);
                if (imageTyepLists.contains(type)) {
                    isImg = 0;
                } else {
                    isImg = 1;
                }
                byte a = 0;
                byte b = 2;
                //获得模块名
                int moduleID = ModuleEnum.IM.getIndex();
                byte mid = (byte) moduleID;
                attachment = new Attachment();
                attachment.setAttachId(attachID);
                attachment.setModule(mid);
                attachment.setAttachFile(fileName);
                attachment.setAttachName(fileName);
                attachment.setYm(ym);
                attachment.setAttachSign(new Long(0));
                attachment.setDelFlag(a);
                attachment.setPosition(b);

                attachment.setFileSize(Convert.convertFileSize(filesize));
                attachment.setSize(Convert.convertFileSize(filesize));
                saveAttachment(attachment);
                attachment = findByLast();
                String attUrl = null;
                if (newFile != null) {
                    String url = newFile.getAbsolutePath();
                    FileInputStream fis = new FileInputStream(newFile);
                    long size = fis.getChannel().size();
                    attUrl = "AID=" + attachment.getAid() + "&" + "MODULE=" + module + "&" + "COMPANY=" + company + "&" + "YM=" + attachment.getYm() + "&" + "ATTACHMENT_ID=" + attachment.getAttachId() + "&" + "ATTACHMENT_NAME=" + attachment.getAttachName() + "&" + "FILESIZE=" + FormetFileSize(size);

                    /*if (isMobile) {
                        attUrl = "AID=" + attachment.getAid() + "&" + "MODULE=" + module + "&" + "COMPANY=" + company + "&" + "YM=" + attachment.getYm() + "&" + "ATTACHMENT_ID=" + attachment.getAttachId() + "&" + "ATTACHMENT_NAME=" + attachment.getAttachName() + "&" + "FILESIZE=" + ReadFile.FormetFileSize(size);

                    } else {
                        attUrl = "AID=" + attachment.getAid() + "&" + "MODULE=" + module + "&" + "COMPANY=" + company + "&" + "YM=" + attachment.getYm() + "&" + "ATTACHMENT_ID=" + attachment.getAttachId() + "&" + "ATTACHMENT_NAME=" + URLEncoder.encode(attachment.getAttachName(), "utf-8") + "&" + "FILESIZE=" + ReadFile.FormetFileSize(size);

                    }*/
                    fis.close();
                    attachment.setUrl(url);
                }
                attachment.setAttUrl(attUrl);
                attachment.setPath(path);
                attachment.setIsImage(isImg);
                list.add(attachment);
            }
        }
        return list;
    }

    public Attachment upload(MultipartFile file, String types, String module, String company, boolean isMobile) throws IOException {

        ResourceBundle rb = ResourceBundle.getBundle("upload");
        String os = System.getProperty("os.name");
        StringBuffer sb = new StringBuffer();
          StringBuffer buffer=new StringBuffer();
        if(os.toLowerCase().startsWith("win")){
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if(uploadPath.indexOf(":")==-1){
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath()+ File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if(basePath.indexOf("/xoa")!=-1){
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2=basePath.substring(0,index);
                }
                sb = sb.append(str2 + "/xoa");
            }
            sb.append(uploadPath);
            buffer=buffer.append(rb.getString("upload.win"));
        }else{
            sb=sb.append(rb.getString("upload.linux"));
            buffer=buffer.append(rb.getString("upload.linux"));
        }
        //当前年月
        String ym = new SimpleDateFormat("yyMM").format(new Date());
        //存储路径
//        String path = sb.toString() + System.getProperty("file.separator") + "attach" + System.getProperty("file.separator") +
//                company + System.getProperty("file.separator") + module + System.getProperty("file.separator") + ym;
        String path = sb.toString() +  System.getProperty("file.separator") +
                company + System.getProperty("file.separator") + module + System.getProperty("file.separator") + ym;

        Attachment attachment = new Attachment();
        if (!file.isEmpty()) {
            // 获得原始文件名
            String fileName = file.getOriginalFilename().trim();
            Long filesize=file.getSize();
            //String fileName = new String(file.getOriginalFilename().getBytes("gbk"),"utf-8");
            String attachID =String.valueOf( Math.abs((int) System.currentTimeMillis()));
            StringBuffer s = new StringBuffer();
            if (os.toLowerCase().startsWith("win")) {
                s.append(fileName);
            } else {
                s.append(fileName);
            }
            String sf = attachID + "." + s.toString();
            String newFileName = sf;
            File dir = new File(path);
            File newFile = null;
            if (!file.isEmpty()) {
                try {
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    newFile = new File(dir, newFileName);
                    // 转存文件
                    if (!newFile.exists()) {
                        newFile.createNewFile();
                    }
                    file.transferTo(newFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            byte isImg = 3;
            //获取后缀名
            String type = fileName.substring(fileName.indexOf(".") + 1);
            String[] imagType = {"jpg", "png", "bmp", "gif", "JPG", "PNG", "BMP", "GIF"};
            List<String> imageTyepLists = Arrays.asList(imagType);
            if (imageTyepLists.contains(type)) {
                isImg = 0;
            } else {
                isImg = 1;
            }
            byte a = 0;
            byte b = 2;
            //获得模块名
            int moduleID = ModuleEnum.IM.getIndex();
            byte mid = (byte) moduleID;
            attachment = new Attachment();
            attachment.setAttachId(attachID);
            attachment.setModule(mid);
            attachment.setAttachFile(fileName);
            attachment.setAttachName(fileName);
            attachment.setYm(ym);
            attachment.setAttachSign(new Long(0));
            attachment.setDelFlag(a);
            attachment.setPosition(b);
            attachment.setSize(Convert.convertFileSize(filesize));
            attachment.setFileSize(Convert.convertFileSize(filesize));
            saveAttachment(attachment);
            attachment = findByLast();
            String attUrl = null;
            if (newFile != null) {
                String url = newFile.getAbsolutePath();
                FileInputStream fis = new FileInputStream(newFile);
                long size = fis.getChannel().size();
                attUrl = "AID=" + attachment.getAid() + "&" + "MODULE=" + module + "&" + "COMPANY=" + company + "&" + "YM=" + attachment.getYm() + "&" + "ATTACHMENT_ID=" + attachment.getAttachId() + "&" + "ATTACHMENT_NAME=" + attachment.getAttachName();

                /*if (isMobile) {
                    attUrl = "AID=" + attachment.getAid() + "&" + "MODULE=" + module + "&" + "COMPANY=" + company + "&" + "YM=" + attachment.getYm() + "&" + "ATTACHMENT_ID=" + attachment.getAttachId() + "&" + "ATTACHMENT_NAME=" + attachment.getAttachName();

                } else {
                    attUrl = "AID=" + attachment.getAid() + "&" + "MODULE=" + module + "&" + "COMPANY=" + company + "&" + "YM=" + attachment.getYm() + "&" + "ATTACHMENT_ID=" + attachment.getAttachId() + "&" + "ATTACHMENT_NAME=" + URLEncoder.encode(attachment.getAttachName(), "utf-8") + "&" + "FILESIZE=" + ReadFile.FormetFileSize(size);

                }*/
                fis.close();
                attachment.setUrl(url);
            }
            attachment.setAttUrl(attUrl);
            attachment.setPath(path);
            attachment.setIsImage(isImg);
        }

        return attachment;
    }


    public String attachmenturl(Attachment att, String company, String module) {
        String attUrl = "AID=" + att.getAid() + "&" + "MODULE=" + module + "&" + "YM=" + att.getYm() + "&" + "ATTACHMENT_ID=" + att.getAttachId() + "&" + "ATTACHMENT_NAME=" + att.getAttachName();
        return attUrl;
    }



    public static String FormetFileSize(long fileS) {//转换文件大小
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if(fileS==0){
            return "0.00B";
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }

}	
